<?php
/**
 * 前端店铺退款业务处理
 * @author ome
 * @access public
 * @copyright www.shopex.net.cn 2010
 *
 */
class ome_rpc_response_refund extends ome_rpc_response
{

    /**
     * 添加退款单
     * @access public
     * @param array $refund_sdf 退款单数据
     * @param object $responseObj 框架API接口实例化对象
     * @return array 退款单主键ID array('refund_id'=>'退款单主键ID')
     */
    function add($refund_sdf, &$responseObj){
        $log = &app::get('ome')->model('api_log');
        $logTitle = '前端店铺退款业务处理[order_bn:'. $refund_sdf['order_bn'] . ']';
        $logInfo = '前端店铺退款业务处理接口：<BR>';
        $logInfo .= '接收参数 $$refund_sdf 信息：' . var_export($refund_sdf, true) . '<BR>';

    	$shop_id = $this->get_shop_id($responseObj);
        $status = $refund_sdf['status'];
        $refund_money = $refund_sdf['money'];
        $refund_bn = $refund_sdf['refund_bn'];
        $refund_type = $refund_sdf['refund_type'];
        $order_bn = $refund_sdf['order_bn'];
        $refundObj = &app::get('ome')->model('refunds');
        $refund_applyObj = &app::get('ome')->model('refund_apply');

        //返回值
        $return_value = array('tid'=>$order_bn,'refund_id'=>$refund_bn,'retry'=>'false');

        //状态值判断
        if ($status==''){
        	$responseObj->send_user_error(app::get('base')->_('Status field value is not correct'), $return_value);
        }
        //退款金额判断
    	if ($refund_money<=0){
    		$responseObj->send_user_error(app::get('base')->_('Money field value is not correct'), $return_value);
        }
    	//判断退款单是否已经存在
        if($refundObj->dump(array('refund_bn'=>$refund_sdf['refund_bn'],'shop_id'=>$shop_id))){
            $logInfo .= '判断退款单是否已经存在，返回值为:<BR>' . var_export($return_value, true) . '<BR>';
            $log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'success', $logInfo);
            
        	return $return_value;
        }
    	if ($refund_bn!='' and $order_bn!=''){

	    	$shop_id = $this->get_shop_id($responseObj);

	        $orderObj = &app::get('ome')->model('orders');
	        $shopObj = &app::get('ome')->model('shop');
        	$oApi_log = &app::get('ome')->model('api_log');
        	$objMath = kernel::single('ectools_math');
	        $order_detail = $orderObj->dump(array('shop_id'=>$shop_id,'order_bn'=>$order_bn), 'pay_status,status,process_status,order_id,payed,cost_payment');
	        $shop_detail = $shopObj->dump($shop_id, 'name,node_type');
        	$shop_name = $shop_detail['name'];
        	$shop_type = $shop_detail['node_type'];
        	$refund_apply = $refund_applyObj->dump(array('refund_apply_bn'=>$refund_bn,'shop_id'=>$shop_id));

    	    //判断订单是否存在
            if(empty($order_detail['order_id'])){
                $msg = 'Order NO:'.$order_bn.' not exists ';
                $return_value['retry'] = 'true';
                $responseObj->send_user_error(app::get('base')->_($msg), $return_value);
                
                $logInfo .= '订单不存在: ' . $msg . '<BR>';
            }

	        //判断订单是否已经支付
            if (in_array($order_detail['pay_status'],array('0','5'))){
            	//日志记录
	        	$api_filter = array('marking_value'=>$refund_bn,'marking_type'=>'refund_payment');
		        $api_detail = $oApi_log->dump($api_filter, 'log_id');
		        if (empty($api_detail['log_id'])){
		            $order_status = kernel::single('ome_order_status')->pay_status($order_detail['pay_status']);
		        	$msg = '订单号：'.$order_detail['order_bn'].',状态:('.$order_status.'),无法退款';
		        	$log_title = '店铺('.$shop_name.')添加退款单号['.$refund_bn.'],'.$msg;
		        	$addon = $api_filter;
		        	$log_id = $oApi_log->gen_id();
		        	$oApi_log->write_log($log_id,$log_title,__CLASS__,__FUNCTION__,'','','response','fail',$msg,$addon);
		        }
            	$responseObj->send_user_error(app::get('base')->_('Order pay '.$order_detail['pay_status'].',can not refund'), $return_value);
            }
    		//判断订单状态是否为活动订单
            if ($order_detail['status']!='active'){
            	//日志记录
	        	$api_filter = array('marking_value'=>$refund_bn,'marking_type'=>'refund_status');
		        $api_detail = $oApi_log->dump($api_filter, 'log_id');
		        if (empty($api_detail['log_id'])){
		        	$msg = '订单号:'.$order_detail['order_bn'].'不是活动订单,无法退款';
		        	$log_title = '店铺('.$shop_name.')添加退款单['.$refund_bn.'],'.$msg;
		        	$addon = $api_filter;
		        	$log_id = $oApi_log->gen_id();
		        	$oApi_log->write_log($log_id,$log_title,__CLASS__,__FUNCTION__,'','','response','fail',$msg,$addon);
		        }
            	$responseObj->send_user_error(app::get('base')->_('Order status is not active，can not refund'), $return_value);
            }
    		//判断订单确认状态
            if ($order_detail['process_status']=='cancel'){
            	//日志记录
	        	$api_filter = array('marking_value'=>$refund_bn,'marking_type'=>'refund_process_status');
		        $api_detail = $oApi_log->dump($api_filter, 'log_id');
		        if (empty($api_detail['log_id'])){
		        	$msg = '订单:'.$order_detail['order_bn'].'确认状态取消,无法退款';
		        	$log_title = '店铺('.$shop_name.')添加退款单['.$refund_bn.'],'.$msg;
		        	$addon = $api_filter;
		        	$log_id = $oApi_log->gen_id();
		        	$oApi_log->write_log($log_id,$log_title,__CLASS__,__FUNCTION__,'','','response','fail',$msg,$addon);
		        }
            	$responseObj->send_user_error(app::get('base')->_('Order is cancel,can not refund'), $return_value);
            }

	        $order_id = $order_detail['order_id'];
            $refund_sdf['t_ready'] = kernel::single('ome_func')->date2time($refund_sdf['t_ready']);
            $refund_sdf['t_sent'] = kernel::single('ome_func')->date2time($refund_sdf['t_sent']);
            $refund_sdf['t_received'] = kernel::single('ome_func')->date2time($refund_sdf['t_received']);
	        if ($status=="succ" || $refund_type == 'refund'){//退款成功

	            $payed_money = $objMath->number_minus(array($order_detail['payed'],$order_detail['cost_payment']));
                //退款金额>已支付金额：返回错误消息
                if ($refund_money > $payed_money){
                    //日志记录
                    $api_filter = array('marking_value'=>$refund_bn,'marking_type'=>'refund_money');
                    $api_detail = $oApi_log->dump($api_filter, 'log_id');
                    if (empty($api_detail['log_id'])){
                        $msg = '订单：'.$order_detail['order_bn'].'退款金额:'.$refund_money.'>已支付金额:'.$payed_money;
                        $log_title = '店铺('.$shop_name.')添加退款单:['.$refund_bn.'],'.$msg;
                        $addon = $api_filter;
                        $log_id = $oApi_log->gen_id();
                        $oApi_log->write_log($log_id,$log_title,__CLASS__,__FUNCTION__,'','','response','fail',$msg,$addon);
                    }
                    $responseObj->send_user_error(app::get('base')->_('refund amount is greater than the amount paid'), $return_value);
                }

                //取出退款申请单据编号
	            if ($refund_sdf['memo']){
                    $refund_apply_bn = '';
                    preg_match("/#(\d+)#/", $refund_sdf['memo'], $refund_apply_bn);
                    $refund_apply_bn = $refund_apply_bn[1];
                    $pattrn = '#'.$refund_apply_bn.'#';
                    $refund_sdf['memo'] = str_replace($pattrn, '', $refund_sdf['memo']);
                }

    	        $pay_bn = $refund_sdf['payment'];
                if ($pay_bn){
                    $payment_cfgObj = &app::get('ome')->model('payment_cfg');
                    $payment_cfg = $payment_cfgObj->dump(array('pay_bn'=>$pay_bn), 'id');
                    $refund_sdf['payment'] = $payment_cfg['id'];
                }

                $sdf = array(
                    'refund_bn' => $refund_bn,
                    'shop_id' => $shop_id,
                    'order_id' => $order_id,
                    'account' => $refund_sdf['account'],
                    'bank' => $refund_sdf['bank'],
                    'pay_account' => $refund_sdf['pay_account'],
                    'currency' => $refund_sdf['currency'],
                    'money' => $refund_money?$refund_money:'0',
                    'paycost' => $refund_sdf['paycost'],
                    'cur_money' => $refund_sdf['cur_money']?$refund_sdf['cur_money']:$refund_sdf['money'],
                    'pay_type' => $refund_sdf['pay_type']?$refund_sdf['pay_type']:'online',
                    'payment' => $refund_sdf['payment'],
                    'paymethod' => $refund_sdf['paymethod'],
                    't_ready' => $refund_sdf['t_ready'] ? $refund_sdf['t_ready'] : $refund_sdf['t_sent'],
                    't_sent' => $refund_sdf['t_sent'] ? $refund_sdf['t_sent'] : $refund_sdf['t_ready'],
                    'download_time' => time(),
                    't_received' => $refund_sdf['t_received'],
                    'status' => $status,
                    'memo' => $refund_sdf['memo'],
                    'trade_no' => $refund_sdf['trade_no']
                );

                $refundObj->create_refunds($sdf);
                $logInfo .= '创建退款单, 参数值为:<BR>' . var_export($sdf, true) . '<BR>';

	            if ($refund_apply['apply_id'] || $refund_apply_bn){
	                //将退款申请单状态变成已退款
    	            $refund_apply_update = array(
                       'status' => '4',
    	               'refunded' => $refund_money,
                    );
                    $refund_bn = $refund_apply_bn ? $refund_apply_bn : $refund_bn;
                    $refund_apply_filter = array(
                       'shop_id' => $shop_id,
                       'refund_apply_bn' => $refund_bn,
                    );
                    $refund_applyObj->update($refund_apply_update, $refund_apply_filter);
                    $logInfo .= '将退款单状态变成已退款，参数为为:<BR>' . var_export($refund_apply_update, true) . '<BR>' . var_export($refund_apply_filter, true) . '<BR>';

                    //更新售后申请单的退款金额
                    $refund_apply_detail = $refund_applyObj->dump($refund_apply_filter, 'addon');
                    $addon = $refund_apply_detail['addon'];
                    if (!empty($addon)){
                        $addon = unserialize($addon);
                        $return_id = $addon['return_id'];
                        $sql = "UPDATE `sdb_ome_return_product` SET `refundmoney`=IFNULL(`refundmoney`,0)+{$refund_money} WHERE `return_id`='".$return_id."'";
                        kernel::database()->exec($sql);
                        
                        $logInfo .= '更新售后申请单的退款金额，返回值为:<BR>' . $sql . '<BR>';
                    }
	            }
	            $this->_updateOrder($order_id,$refund_money);
	            
	            $logInfo .= '更新订单 ' . $order_id . ' 状态及金额 ' . $refund_money . '<BR>';
	        }elseif ($refund_type == 'apply'){

	            //判断申请退款单是否已经存在
	            if ($refund_apply['apply_id'] && $status == '0'){
	                $logInfo .= '申请退款单是否已经存在 且status等于0，返回值为:<BR>' . var_export($return_value, true) . '<BR>';
                    $log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'success', $logInfo);
            
	               return $return_value;
	            }
	            if ($status == '0'){
    	            $addon = serialize(array('refund_bn'=>$refund_bn));
    	            $sdf = array(
                        'order_id' => $order_id,
    	                'refund_apply_bn' => $refund_bn,
        	            'pay_type' => $refund_sdf['pay_type']?$refund_sdf['pay_type']:'online',
        	            'account' => $refund_sdf['account'],
        	            'bank' => $refund_sdf['bank'],
        	            'pay_account' => $refund_sdf['pay_account'],
        	            'money' => $refund_money?$refund_money:'0',
        	            'refunded' => '0',
        	            'memo' => $refund_sdf['memo'],
        	            'create_time' => $refund_sdf['t_ready'],
        	            'status' => $status,
                        'shop_id' => $shop_id,
    	                'addon' => $addon,
                    );
                    $refund_applyObj->create_refund_apply($sdf);
                    
                    $logInfo .= '创建退款申请单，参数值为:<BR>' . var_export($sdf, true) . '<BR>';
	            }else{
	                $refund_apply_update = array(
	                   'status' => $status,
	                );
	                $refund_apply_filter = array(
	                   'shop_id' => $shop_id,
	                   'refund_apply_bn' => $refund_bn,
	                );
	                $refund_applyObj->update($refund_apply_update, $refund_apply_filter);
	                
	                $logInfo .= '更新退款申请单状态，参数值为:<BR>' . var_export($refund_apply_update, true) . '<BR>' . var_export($refund_apply_filter, true) . '<BR>';
	            }
	            //更新订单支付状态
                kernel::single('ome_order_func')->update_order_pay_status($order_id);
                
                $logInfo .= '更新订单：' . $order_id . '支付状态<BR>';
	        }
	        
	        $logInfo .= '返回值为:<BR>' . var_export($return_value, true) . '<BR>';
            $log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'success', $logInfo);
            
        	return $return_value;
    	}else{
    		$responseObj->send_user_error(app::get('base')->_('Refund_bn and Order_bn can not be empty'), $return_value);
    	}

        $log->write_log($log->gen_id(), $logTitle, __CLASS__, __METHOD__, '', '', 'response', 'success', $logInfo);
    }

    /**
     * 更新退款单状态
     * @access public
     * @param array $status_sdf 退款单状态数据
     * @param object $responseObj 框架API接口实例化对象
     */
    function status_update($status_sdf, &$responseObj){

        $status = $status_sdf['status'];
        $refund_bn = $status_sdf['refund_bn'];
        $order_bn = $status_sdf['order_bn'];

        //返回值
        $return_value = array('tid'=>$order_bn,'refund_id'=>$refund_bn);

        //状态值判断
        if ($status==''){
        	$responseObj->send_user_error(app::get('base')->_('Status field value is not correct'), $return_value);
        }
    	if ($refund_bn!='' and $order_bn!=''){

    		$shop_id = $this->get_shop_id($responseObj);
	        $orderObj = &app::get('ome')->model('orders');
	        $refundObj = &app::get('ome')->model('refunds');
	        $order_detail = $orderObj->dump(array('shop_id'=>$shop_id,'order_bn'=>$order_bn), 'order_id');
	        $refund_detail = $refundObj->dump(array('refund_bn'=>$refund_bn,'shop_id'=>$shop_id));

	        $order_id = $order_detail['order_id'];
    		if ($status=="succ"){//已支付

    			//更新退款单状态
    			$filter = array('refund_bn'=>$refund_bn,'shop_id'=>$shop_id);
    			$data = array('status'=>$status);
    			$refundObj->update($data, $filter);
    			//更新订单状态
	        	$this->_updateOrder($order_id,$refund_detail['money']);
	        }

            return $return_value;

    	}else{
    		$responseObj->send_user_error(app::get('base')->_('Refund_bn and Order_bn can not be empty'), $return_value);
    	}
    }

    /**
     * 更新订单状态及金额
     * @access private
     * @param string order_id
     * @param string shop_id
     * @param money refund_money
     * @return boolean
     */
    private function _updateOrder($order_id, $refund_money){
        if (empty($order_id)) return false;

        //更新订单支付金额
        if ($refund_money){
        	$sql ="update sdb_ome_orders set payed=IF((CAST(payed AS char)-IFNULL(0,cost_payment)-".$refund_money.")>=0,payed-IFNULL(0,cost_payment)-".$refund_money.",0)  where order_id=".$order_id;
    		kernel::database()->exec($sql);
        }

		//更新订单支付状态
		if (kernel::single('ome_order_func')->update_order_pay_status($order_id)){
		    return true;
		}else{
		    return false;
		}
    }


}